import { login as loginAPI } from "@/api";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter } from "@/router";
import { constantRoutes, asyncRoutes, anyRoute } from "@/router/routes";
import router from "@/router";
import Router from 'vue-router'
import cloneDeep from "lodash/cloneDeep";
/**
 * 递归过滤异步路由表，返回符合用户菜单权限的路由表
 * @param asyncRoutes 动态路由
 * @param routeNames 当前用户所拥有的权限
 */

// 过滤动态路由
const filterRoutes = (allAsyncRoutes, routes) => {
  return allAsyncRoutes.filter(route => {
    if (routes.includes(route.name)) {
      if (route.children && route.children.length) {
        filterRoutes(routes, route.children)
      }
      return true
    }
    return false
  })
}
const getDefaultState = () => {
  return {
    token: getToken(),
    name: "",
    avatar: "",

    roles: [],
    buttons: [],
    routes: [], // 本用户所有的路由,包括了固定的路由和下面的addRouters
    asyncRoutes: [], // 本用户的角色赋予的新增的动态路由
  };
};

const state = getDefaultState();

const mutations = {
  SET_USER: (state, userInfo) => {
    state.name = userInfo.name; // 用户名
    state.avatar = userInfo.avatar; // 头像
    state.roles = userInfo.roles; // 角色列表
    state.buttons = userInfo.buttons; // 按钮权限列表
  },

  SET_TOKEN(state, token) {
    state.token = token;
  },

  RESET_USER(state) {
    Object.assign(state, getDefaultState());
  },

  SET_ROUTES: (state, asyncRoutes) => {
    // 保存异步路由
    state.asyncRoutes = asyncRoutes;
    // 合并常量路由,异步路由与备选路由, 并保存
    const allRoutes = constantRoutes.concat(asyncRoutes, anyRoute)
    state.routes = allRoutes //将固定路由和新增路由进行合并, 成为本用户最终的全部路由信息
    // 将当前用户的异步权限路由和备选路由添加到路由器
    router.matcher = new Router().matcher //match
    router.addRoutes(allRoutes)

  },
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      loginAPI
        .login(username, password)
        .then((result) => {
          const { data } = result;
          commit("SET_TOKEN", data.token);
          setToken(data.token);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // 获取用户信息
  async getInfo({ commit, state }) {
    const { data } = await loginAPI.getInfo();
    commit("SET_USER", data);

    // commit('SET_ROUTES', filterAsyncRoutes(data.routes))
    commit('SET_ROUTES', filterRoutes(cloneDeep(asyncRoutes), data.routes))
  },

  /* 
  重置用户信息
  */
  async resetUser({ commit, state }) {
    // 如果当前是登陆的, 请求退出登陆
    if (state.name) {
      await loginAPI.logout();
    }
    // 删除local中保存的token
    removeToken();
    // 重置路由
    resetRouter();
    // 提交重置用户信息的mutation
    commit("RESET_USER");
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
